﻿using RFID_EX_ETC_Client.Utils;
using RFID_EX_WineSecurity.Core;
using RFID_EX_WineSecurity.Dao;
using RFID_EX_WineSecurity.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RFID_EX_WineSecurity {
    public partial class MainForm : Form {

        private DBHelper dBHelper;
        public MainForm() {
            InitializeComponent();
            this.Text = GlobalVariable.APP_NAME;
            dBHelper = new DBHelper();
        }

        //为true，已经连接设备
        private bool isConnect = false;

        private void Form1_Load(object sender, EventArgs e) {
            InitView();
            PrintDeviceInfo();
            if (cb_ComNum.Items.Count <= 0) {
                //若没有串口设备，弹出提示
                MessageBox.Show("没有发现任何串口设备", "错误");
                return;
            }
            //设置默认串口
            //cb_ComNum.SelectedIndex = 0;
        }

        private void InitView() {
            //获取所有串口设备
            GetAllSerialPort();
        }

        private void PrintDeviceInfo() {
            uint libVersion = new uint();
            int status = RFIDReader.lib_ver(ref libVersion);
            if (status == 0) {
                LogUtil.WriteLine("动态库版本:"+libVersion);
            }
        }


        /**
         * UI更新
         * *****************************************************************************/
        private void GetAllSerialPort() {
            string[] ports = SerialPort.GetPortNames();
            foreach (string port in ports) {
                cb_ComNum.Items.Add(port);
            }
        }

        private delegate void UpdateDevStateDelegate(bool isCon);
        private void UpdateDevState(bool isCon) {
            if (btn_LinkSP.InvokeRequired) {
                this.Invoke(new UpdateDevStateDelegate(UpdateDevState), isCon);
            } else {
                if (isCon) {
                    isConnect = true;
                    lb_devStat.Text = "已连接";
                    btn_LinkSP.Text = "断开连接";
                } else {
                    isConnect = false;
                    lb_devStat.Text = "未连接";
                    btn_LinkSP.Text = "连接设备";
                }
            }
        }

        private delegate void SetTagIDDelegate(string tagID);
        private void SetTagID(string tagID) {
            if (tb_TagID.InvokeRequired) {
                this.Invoke(new SetTagIDDelegate(SetTagID), tagID);
            } else {
                tb_TagID.Text = tagID;
            }
        }

        private delegate void SetBottomMessageDelegate(string message);
        private void SetBottomMessage(string message) {
            if (lb_result.InvokeRequired) {
                this.Invoke(new SetBottomMessageDelegate(SetBottomMessage), message);
            } else {
                lb_result.Text = message;
            }
        }

        /**
         * 事件处理
         * ******************************************************************************/
        
        private void btn_LinkSP_Click(object sender, EventArgs e) {
            if (!isConnect) {
                string portStr = cb_ComNum.Text.Trim();
                if ("".Equals(portStr)) {
                    SetBottomMessage("未选择串口!");
                    return;
                }
                //Console.WriteLine(portStr);
                int port = Convert.ToInt32(portStr.Substring("COM".Length));
                //连接设备 
                int status = RFIDReader.rf_init_com(RFIDReader.IcDev, port, RFIDReader.BaudRate);
                if (status == 0) {
                    UpdateDevState(true);
                    SetBottomMessage("连接成功");
                } else {
                    isConnect = false;
                    SetBottomMessage("连接失败");
                }
            } else {
                int status = RFIDReader.rf_ClosePort();
                UpdateDevState(false);
                SetBottomMessage("断开连接成功");
            }
            
        }

        private void btn_Find_Click(object sender, EventArgs e) {
            if (!isConnect) {
                // MessageBox.Show("设备未连接!", GlobalVariable.TIP_TITLE);
                SetBottomMessage("设备未连接!");
                return;
            }
            int status = -1;
            ushort tagtype = 0;   //接收卡片类型值，TYPE_A
            //寻卡
            status = RFIDReader.rf_request(RFIDReader.IcDev, RFIDReader.REQUES_MODE_ALL, ref tagtype);
            if (status != 0) {
                SetBottomMessage("寻卡失败");
                return;
            }
            SetBottomMessage("寻卡成功");

            //防冲突
            byte bcnt = 0x04;     //卡序列号字节数
            byte[] pSnr = new byte[10];   //卡序列号
            byte pRLength = 0;        //卡序列号长度
            status = RFIDReader.rf_anticoll(RFIDReader.IcDev, bcnt, ref pSnr[0], ref pRLength);
            if (status != 0) {
                SetBottomMessage("防冲突失败");
                return;
            }
            SetBottomMessage("防冲突成功");
            //读出标签ID
            StringBuilder sb = new StringBuilder("");
            for (int i = 0; i < pRLength; i++) {
                sb.Append(pSnr[i].ToString("X2"));
            }
            string result = sb.ToString();

            //选卡
            sbyte Size = 0;
            status = RFIDReader.rf_select(RFIDReader.IcDev, ref pSnr[0], bcnt, ref Size);
            if (0 != status) {
                SetBottomMessage("选卡失败");
                return;
            }
            SetBottomMessage("选卡成功");
            SetTagID(result);
        }

        private void btn_Clear_Click(object sender, EventArgs e) {
            tb_TagID.Text = "";
            SetBottomMessage("");
        }

        private void btn_Flash_Click(object sender, EventArgs e) {
            cb_ComNum.Items.Clear();
            GetAllSerialPort();
            if (cb_ComNum.Items.Count > 0) {
            //    cb_ComNum.SelectedIndex = 0;
            }
        }

        private void btn_Setting_Click(object sender, EventArgs e) {
            new SettingForm().ShowDialog();
        }

        private void btn_Enter_Click(object sender, EventArgs e) {
            string tagId = tb_TagID.Text.Trim();
            if ("".Equals(tagId)) {
                SetBottomMessage("标签ID不能为空!");
                return;
            }
            Thread thread =  new Thread(AddTagRunable);
            thread.Start(tagId);
        }

        private void btn_check_Click(object sender, EventArgs e) {
            string tagId = tb_TagID.Text.Trim();
            if ("".Equals(tagId)) {
                SetBottomMessage("标签ID不能为空!");
                return;
            }
            Thread thread = new Thread(CheckTagRunable);
            thread.Start(tagId);
        }

        private void AddTagRunable(object tagId) {
            bool result = dBHelper.AddTag((string)tagId);
            if (result) {
                SetBottomMessage("录入成功");
            } else {
                SetBottomMessage("录入失败");
            }
        }

        private void CheckTagRunable(object tagId) {
            bool result = dBHelper.QueryTag((string)tagId);
            if (result) {
                SetBottomMessage("该酒为正品");
            } else {
                SetBottomMessage("查询不到相关数据");
            }
        }
    }
}
